#!/usr/bin/env python
# -*- coding: utf-8 -*-

import jinja2
import webapp2
import random
import json
import datetime

import os
#from google.appengine.ext.webapp import template

from xlscreator import XLS_creator

from db.exceptions import *
from db.userData import UserData, db

from handlers.myhandler import *
from handlers.azienda import AziendeHandler
from handlers.userhandler import UserHandler
from handlers.sessionhandler import SessionHandler
from handlers.projecthandler import ProjectHandler
from handlers.invoicehandler import InvoiceHandler
from handlers.invoicesettingshandler import InvoiceSettingsHandler
from handlers.invoicetaxeshandler import InvoiceTaxesHandler

JINJA_ENVIRONMENT = jinja2.Environment(
    autoescape=True,
    loader=jinja2.FileSystemLoader([
    	os.path.dirname(__file__),
    	os.path.join(os.path.dirname(__file__), 'templates')]
    )
)

# devo scegliere lo xor preferito ^^
def xor(*args):
	return not all(args) and any(args)
def xor2(a, b):
	(False if a else b) if b else a
def xor3(a, b):
	(not b and a) or (not a and b)
def xor4(a, b):
	return bool(a)+bool(b)==1
def xor5(a, b):
	return bool(a)^bool(b)

class MainHandler(MyHandler):
	
	def safeGet(self, user):
		
			print "processing page request..."
			
			path = 'index.html'
			
			userstate = 0
			if user:
				if UserData.exist(user) or self.request.get('skip'):
					userstate = 2
				else:
					userstate = 1
			
			if userstate>0:
				path = 'index.html'
				template_values = {
					'datetime':datetime.datetime.utcnow().strftime("%d/%m/%y %X"),
					'init_string': user.nickname() or user.email(),
					'redirect_url':users.create_logout_url('/')
				}
			else:
				path = 'welcome.html'
				template_values = {
					'redirect_url': users.create_login_url(self.request.uri)
				}
				
			
			#path = os.path.join(os.path.dirname(__file__), path)
			#self.response.out.write(template.render(path, template_values))

			template = JINJA_ENVIRONMENT.get_template(path)
			self.response.write(template.render(template_values))
	
	def needAuth(self):
		return False


# class GetXls(MyHandler):
# 	def safeGet(self, user):
		
# 		params = self.getAllParametersInDict()
# 		userData = UserData.getUserData(user)[0]
# 		aziendaData = None
# 		proj = None
		
# 		if params['azienda']:
# 			aziendaData = db.get(params['azienda']).myserialize()
# 			sessionSum = SessionData.getSumBetween(user, azienda=params['azienda'], start=params['start'], end=params['end'])
# 		elif params['progetto']:
# 			proj = db.get(params['progetto'])
# 			aziendaData = proj.azienda.myserialize()
# 			sessionSum = proj.eur
# 		else:
# 			self.sendError(MyException(), 'Si &egrave; verificato un errore!')
		
# 		msg = ('msg' in params) and params['msg'] or "Messaggio di prova"
		
# 		try:
# 			date = ('date' in params) and datetime.datetime.strptime(params['date'], "%m/%d/%Y") or datetime.datetime.now()
# 		except:
# 			date = datetime.datetime.now()
# 		xls = XLS_creator(userdata=userData, azienda=aziendaData, sessionSum=sessionSum, msg=msg, date=date)

# 		# HTTP headers to force file download
# 		self.response.headers['Content-Type'] = 'application/ms-excel'
# 		self.response.headers['Content-Transfer-Encoding'] = 'Binary'
# 		self.response.headers['Content-disposition'] = 'attachment; filename="Diaria_test.xls"'

# 		# output to user
# 		xls.save(self.response.out)
# 		if proj:
# 			proj.closeProj()

from db.aziendaData import AziendaData
from db.invoiceData import InvoiceData
from db.projectData import ProjectData
from db.invoiceSettings import InvoiceSettings

class InvoicePreviewHandler(MyHandler):

	def safeGet(self, user):

		path = self.request.path_info[1:].split("/")
		#if not len(path)>1:
		#	raise InexistentKeyException
		params = {}
		if len(path)<3:
			raise Exception()
		key = path[2]

		fattura = InvoiceData.getSingleInvoiceData(user, key)
		invoice_settings = InvoiceSettings.getRawInvoiceSettings(user)
		user_data = UserData.getRawUserData(user)
		project_data = ProjectData.getSingleProjectRawData(user, fattura['project'])
		customer_data = project_data.customer#AziendaData.getSingleCustomerRawData(user, project_data.customer)

		invoice_sum = 0 #float(fattura['amount'])
		invoice_imponibile = 0 #float(fattura['amount'])

		for row in fattura['rows']:
			row['amount'] = float(row['amount'])
			invoice_sum += row['amount']

		invoice_imponibile = invoice_sum

		for element in fattura['additionals']:
			print element
			if element['type']=="percentage":
				calc = invoice_imponibile * float(element['value']) / 100
				element['calc_value'] = calc
				element['label_value'] = ""+str(element['value'])+"%"
				invoice_sum += calc
			else:
				calc = float(element['value'])
				element['calc_value'] = calc
				element['label_value'] = ""
				invoice_sum += calc

		page_template = JINJA_ENVIRONMENT.get_template("print_invoices.html")
		page_template_values = {
			'user_firstName': user_data.firstName,
			'user_lastName': user_data.lastName,
			'user_vatNumber': user_data.vatNumber,
			'user_iban': user_data.iban,
			'user_street': user_data.street,
			'user_zipCode': user_data.zipCode,
			'user_city': user_data.city,
			'project_name': project_data.name,
			'customer_name': customer_data.name,
			'customer_vatNumber': customer_data.piva,
			'customer_street': customer_data.street,
			'customer_zipCode': customer_data.zipCode,
			'customer_city': customer_data.city,
			'invoiceFooter': invoice_settings.invoiceFooter or "",
			'invoiceHeader': invoice_settings.invoiceHeader or "",
			'datetime':datetime.datetime.utcnow().strftime("%d/%m/%y %X"),
			'date':datetime.datetime.utcnow().strftime("%d/%m/%y"),
			'time':datetime.datetime.utcnow().strftime("%X"),
			'chiave_fattura': key,
			'imponibile': invoice_imponibile,
			'invoiceNumber': fattura['invoiceNumber'],
			'rivalsa_inps': "non te la do'!!",
			'additionals':fattura['additionals'],
			'rows':fattura['rows'],
			'totale': invoice_sum
		}
		page_html = page_template.render(page_template_values)
		second_step_template = jinja2.Template(page_html)
		second_step_page_html = second_step_template.render(page_template_values)
		self.response.write(second_step_page_html)
		return

		# invoice_template_path = "templates/invoice.html"
		# invoice_template_path = os.path.join(os.path.dirname(__file__), invoice_template_path)
		# invoice_template_values = {
		# 	'invoiceFooter': invoice_settings.invoiceFooter,
		# 	'invoiceHeader': invoice_settings.invoiceHeader,
		# 	'datetime':datetime.datetime.utcnow().strftime("%d/%m/%y %X"),
		# 	'date':datetime.datetime.utcnow().strftime("%d/%m/%y"),
		# 	'time':datetime.datetime.utcnow().strftime("%X"),
		# 	'chiave_fattura': key,
		# 	'valore_fattura': fattura.amount,
		# 	'invoiceNumber': fattura.invoiceNumber,
		# 	'rivalsa_inps': "non te la do'!!"
		# }
		# #invoice_html = template.render(invoice_template_path, invoice_template_values)

		# template = JINJA_ENVIRONMENT.get_template("invoice.html")
		# invoice_html = template.render(invoice_template_values)

		# page_path = "print_invoices.html"
		# #page_path = os.path.join(os.path.dirname(__file__), page_path)
		# page_template_values = {
		# 	'template_invoice': invoice_html
		# }
		# #self.response.out.write(template.render(page_path, page_template_values))

		# page_template = JINJA_ENVIRONMENT.get_template(page_path)
		# self.response.write(page_template.render(page_template_values))
		# return



app = webapp2.WSGIApplication([('/', MainHandler), 
							   #('/download', GetXls), 
							   ('/user', UserHandler), 
							   ('/customers[/]?.*', AziendeHandler),
							   ('/projects[/]?.*', ProjectHandler),
							   ('/sessions', SessionHandler),
							   ('/invoices/preview[/]?.*', InvoicePreviewHandler),
							   ('/invoice/settings/taxes[/]?.*', InvoiceTaxesHandler),
							   ('/invoice/settings[/]?.*', InvoiceSettingsHandler),
							   ('/invoices[/]?.*', InvoiceHandler),
							], debug=True)
